"""
使用百度翻译API的翻译服务器
免费版每秒1次请求，每月100万字符
注册地址：https://fanyi-api.baidu.com/
"""

from flask import Flask, request, jsonify
from flask_cors import CORS
import hashlib
import random
import requests

app = Flask(__name__)
CORS(app)

# 百度翻译API配置
# 请在这里填入你的APP ID和密钥
BAIDU_APPID = 'YOUR_APP_ID'  # 替换为你的APP ID
BAIDU_SECRET_KEY = 'YOUR_SECRET_KEY'  # 替换为你的密钥
BAIDU_API_URL = 'https://fanyi-api.baidu.com/api/trans/vip/translate'

def baidu_translate(text, from_lang='en', to_lang='zh'):
    """
    使用百度翻译API进行翻译
    """
    if BAIDU_APPID == 'YOUR_APP_ID' or BAIDU_SECRET_KEY == 'YOUR_SECRET_KEY':
        return f"[需配置] {text} (请在代码中填入百度翻译API的APP ID和密钥)"
    
    # 生成随机数
    salt = str(random.randint(32768, 65536))
    
    # 生成签名
    sign_str = BAIDU_APPID + text + salt + BAIDU_SECRET_KEY
    sign = hashlib.md5(sign_str.encode('utf-8')).hexdigest()
    
    # 构建请求参数
    params = {
        'q': text,
        'from': from_lang,
        'to': to_lang,
        'appid': BAIDU_APPID,
        'salt': salt,
        'sign': sign
    }
    
    try:
        response = requests.get(BAIDU_API_URL, params=params, timeout=5)
        result = response.json()
        
        if 'trans_result' in result:
            return result['trans_result'][0]['dst']
        elif 'error_code' in result:
            error_msg = result.get('error_msg', '未知错误')
            return f"[翻译错误] {error_msg}"
        else:
            return "[翻译失败] 返回结果格式错误"
    except Exception as e:
        return f"[请求失败] {str(e)}"

@app.route('/translate', methods=['POST'])
def translate():
    """
    翻译API端点
    """
    try:
        data = request.json
        text = data.get('text', '')
        
        if not text:
            return jsonify({'error': '文本为空'}), 400
        
        # 如果文本太长，截取前5000个字符
        if len(text) > 5000:
            text = text[:5000]
        
        translation = baidu_translate(text)
        return jsonify({'translation': translation})
    
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/health', methods=['GET'])
def health():
    """
    健康检查端点
    """
    configured = BAIDU_APPID != 'YOUR_APP_ID' and BAIDU_SECRET_KEY != 'YOUR_SECRET_KEY'
    return jsonify({
        'status': 'ready' if configured else 'need_config',
        'api': 'baidu_translate',
        'configured': configured
    })

if __name__ == '__main__':
    print("=" * 60)
    print("百度翻译API服务器启动中...")
    print("=" * 60)
    
    if BAIDU_APPID == 'YOUR_APP_ID' or BAIDU_SECRET_KEY == 'YOUR_SECRET_KEY':
        print("\n⚠️  警告：百度翻译API未配置")
        print("\n配置步骤：")
        print("1. 访问 https://fanyi-api.baidu.com/")
        print("2. 注册并申请通用翻译API")
        print("3. 获取APP ID和密钥")
        print("4. 在本文件中填入APP ID和密钥（第13-14行）")
        print("\n免费版额度：每秒1次请求，每月100万字符\n")
    else:
        print("\n✓ 百度翻译API已配置")
    
    print("\n服务器地址: http://localhost:5000")
    print("翻译接口: POST http://localhost:5000/translate")
    print("健康检查: GET http://localhost:5000/health")
    print("\n按 Ctrl+C 停止服务器")
    print("=" * 60)
    
    app.run(host='0.0.0.0', port=5000, debug=False)